/***
	Copyright (c) 2010 CommonsWare, LLC
	
	Licensed under the Apache License, Version 2.0 (the "License"); you may
	not use this file except in compliance with the License. You may obtain
	a copy of the License at
		http://www.apache.org/licenses/LICENSE-2.0
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/

package com.touringapp.android.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.widget.Toast;
/***
	Copyright (c) 2010 CommonsWare, LLC
	
	Licensed under the Apache License, Version 2.0 (the "License"); you may
	not use this file except in compliance with the License. You may obtain
	a copy of the License at
		http://www.apache.org/licenses/LICENSE-2.0
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/

import java.util.Date;
import java.util.LinkedList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.commonsware.cwac.locpoll.LocationPoller;
import com.touringapp.android.activity.MainActivity;
import com.touringapp.android.utils.http.RequestUtility;

public class LocationReceiver extends BroadcastReceiver {
	private static Object lock = new Object();
	private static final LinkedList<com.touringapp.android.activity.Location> locations = new LinkedList<com.touringapp.android.activity.Location>();
	private static Long lastTimeCheckedIn = null;
	private static Long CHECK_IN_INTERVAL = 10000l;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		Location loc= (Location) intent.getExtras().get(LocationPoller.EXTRA_LOCATION);
		if (loc != null) {
			addLocation(context, loc);
		}
	}
	
	private static void addLocation(final Context context, Location location) {
		synchronized (lock) {
	        Toast.makeText(context,
                    "received location + lat=" + location.getLatitude() + ", long=" + location.getLongitude(),
                    Toast.LENGTH_LONG).show();
			
			locations.add(new com.touringapp.android.activity.Location(
					location.getLatitude(), location.getLongitude(), location.hasSpeed() ? (double)location.getSpeed() : null,
							location.hasAccuracy() ? (double)location.getAccuracy() : null, new Date()));
			long currentTime = System.currentTimeMillis();
			if (lastTimeCheckedIn == null || currentTime <= lastTimeCheckedIn || currentTime - CHECK_IN_INTERVAL > lastTimeCheckedIn) {
				new CheckInThread(context).start();
			}
		}
	}
	
    private static String DEVICE_ID = null;
    public static String getDeviceId(final Context context) {
        if (DEVICE_ID == null) {
            DEVICE_ID = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        }
        return DEVICE_ID;
    }

	
	private static class CheckInThread extends Thread {
		private Context context;
		
		public CheckInThread(Context context) {
			this.context = context;
		}

		@Override
		public void run() {
			final String userName = MainActivity.userName;
			if (userName == null || userName.trim().length() == 0 || locations.size() == 0) {
				return;
			}
			try {
				JSONObject checkInRequest = null;
				synchronized (lock) {
					final String deviceId = getDeviceId(context);
					checkInRequest = new JSONObject();
					checkInRequest.put("name", userName);
					checkInRequest.put("deviceId", deviceId);
					JSONArray locationArray = new JSONArray();
					int i = 0;
					for (com.touringapp.android.activity.Location location : locations) {
						locationArray.put(i++, location.toJSON());
					}
					checkInRequest.put("locations", locationArray);
				}
				
				RequestUtility.executePostRequest("http://touring-engine.appspot.com/user/checkin", checkInRequest);
				synchronized (lock) {
					lastTimeCheckedIn = System.currentTimeMillis();
					locations.clear();
				}					
			} catch (Exception ex) {
				//no need to do anything;
			}
		}
	}
	
	public static void clear() {
		synchronized (lock) { 
			lastTimeCheckedIn = null;
			locations.clear();
		}
	}
}